package com.nulldev.util.web.nTube.util;

import java.io.Reader;
import java.io.StringReader;
import java.util.List;

import com.nulldev.util.VariableAPI.StringsUtil;
import com.nulldev.util.data.legacy.XML.lXML;
import com.nulldev.util.data.legacy.XML.lXML.E;
import com.nulldev.util.data.legacy.XML.lXML.Node;
import com.nulldev.util.io.file.FileUtil;
import com.nulldev.util.web.HttpServer3.pages.v3.HttpPage3.Request;
import com.nulldev.util.web.nTube.pages.Urlizer;
import com.nulldev.util.web.nTube.pages.Urlizer.UrlizerOptions;

public class DashMPDTranslator {

	public static String translate(final Request req, final String xml) {
		return translate(req, new StringReader(xml));
	}

	public static String translate(final Request request, final Reader xml) {
		final String _intUrl;
		/* HttpServer mandates the Host header from 3.0.6 */
		final String _hdr = request.header("Host", "");
		if (!StringsUtil.isZeroLengthOrNull(_hdr)) {
			if (NTubeUtils.wasOriginHTTPS(request)) {
				_intUrl = "https://" + _hdr;
			} else {
				_intUrl = "http://" + _hdr;
			}
		} else {
			_intUrl = _hdr;
		}
		final lXML.Doc d = lXML.doc(xml);
		final lXML.E root = (E) d.children().get(1);
		if (root.name().equalsIgnoreCase("MPD")) {
			final lXML.E segmentList = (E) root.children().get(0);
			if (segmentList == null)
				throw new NullPointerException("segmentList == null!");
			for (final Node _child : segmentList.children()) {
				final lXML.E child = (E) _child;
				if (child.name().equalsIgnoreCase("AdaptationSet")) {
					final List<E> representations = child.children("Representation");
					for (final E representation : representations) {
						final E baseURL = representation.child("BaseURL");
						if (baseURL == null)
							continue;
						final String url = baseURL.text();
						final String out = _intUrl + Urlizer.urlizer(url, UrlizerOptions.PUT_METADATA_AT_START, UrlizerOptions.SEND_TRANSLATOR_URL_HINT);
						baseURL.setText(out);
					}
				} else
					continue;
			}
			return d.toString();
		} else
			throw new UnsupportedOperationException("Unknown root: " + root.name());
	}

	public static void main(String[] args) throws Exception {
		translate(Request.dummy(), FileUtil.readFileToString(FileUtil.safeCreate(FileUtil.HOME_DIRECTORY + "/test.mpd")));
	}
}
